package org.wt.phoenix.middleware.shardingsphere.mockroute.route.handler;

import groovy.lang.Closure;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.apache.shardingsphere.core.yaml.config.sharding.strategy.YamlInlineShardingStrategyConfiguration;
import org.wt.phoenix.middleware.shardingsphere.mockroute.domain.HandlerContext;

public class InlineShardingStrategyHandler implements ShardingStrategyHandler{
    private static final GroovyShell SHELL = new GroovyShell();

    @Override
    public String handler(HandlerContext context) {
        YamlInlineShardingStrategyConfiguration inlineConfig = (YamlInlineShardingStrategyConfiguration) context.getStrategyConfiguration();

        String shardingColumn = inlineConfig.getShardingColumn();
        if (!shardingColumn.equals(context.getColumn())){
            throw new RuntimeException("不支持的列名:" + context.getColumn() + ",分表列为：" + shardingColumn);
        }

        String expression = inlineConfig.getAlgorithmExpression();
        String[] split = expression.split("\\$");
        int index = split[1].indexOf("{");
        expression = split[0] + "$" + split[1].substring(index, split[1].length());

        Script script = SHELL.parse("{it -> \"" + expression + "\"}");
        Closure closure = (Closure) script.run();
        closure.setResolveStrategy(Closure.DELEGATE_ONLY);
        closure.setProperty(shardingColumn, context.getShardingValue());
        return  closure.call().toString();
    }
}
